<template>
	<view class="sigin">
		<view class="nav" :style="{ background: showBg ? '#fff' : '' }">
			<global-nav-bar :isLeftBack="false" @clickLeft="backFuc" type="black" left-icon="back" color="#333"
				:title="signType == 1 ? '签到' : '签退'" :fixed="false" backgroundColor="rgba(0, 0, 0, 0)"></global-nav-bar>
		</view>
		<view>
			<image class="bg"
				src="https://592800-erised-fresh.oss-cn-shenzhen.aliyuncs.com/upload/20221012/c1a6e9996af7e11408d283b788eb2b33.png"
				mode="" v-if="!showBg"></image>
		</view>
		<view class="title">
			<view class="left">{{
				elevatorDetail.elevatorAddress || offlineDetail.elevatorAddress
			}}</view>
		</view>
		<view class="content">
			<view class="content_item top">
				<view class="name">
					<image src="@/static/images/index/dw.png" mode="" />
					<view class="label buildName">
						{{ elevatorDetail.buildingName || offlineDetail.buildingName }}
					</view>
				</view>
				<view class="error" v-if="locationError != '正常'">{{
					locationError
				}}</view>
			</view>
			<view class="content_item top" style="flex-wrap: wrap">
				<view class="name"> 电梯状态 </view>
				<view class="status-btns">
					<view :class="['status-btns-item', isStop == 1 ? 'status-act' : '']" @click="handleClickStatus(1)">
						正常运行</view>
					<view :class="['status-btns-item', isStop == 2 ? 'status-act' : '']" @click="handleClickStatus(2)">
						停梯</view>
				</view>

			</view>
			<view class="content_item" v-if="orderType == 1 && signType == 1 && onlineStatus">
				<view class="label">系统预估耗时</view>
				<view class="timeArea">
					<text style="color: #0091ff">{{ systemTime.hour }}小时{{ systemTime.min }}分</text>
				</view>
			</view>

			<view class="content_item" v-if="showFinshTime">
				<view class="label">{{ `预计${orderType == 1 ? "保养" : "维修"}` }}结束时间</view>
				<view class="timeArea" @click="showChooseDate" v-if="dateArr.length">
					<text>{{ `${dateArr[0]}年` }}</text>
					<text style="color: #0091ff">
						{{ `${dateArr[1]}月${dateArr[2]}日` }}
						<text v-if="todayStr">{{ `(${todayStr})` }}</text>
						{{ `${dateArr[3]}:${dateArr[4]}` }}
					</text>

					<image src="@/static/images/edit2.png" mode="" />
				</view>
			</view>
			<view class="imgbox" v-if="isTakePhoto">
				<view class="label">{{ signType == "1" ? "入场照" : "退场照" }} </view>
				<view class="guide" @click="openGuide" v-if="(orderType == 1||orderType == 2) && guide.desc">
					<image class="guide-ico" src="@/static/images/guide.svg"></image>
					拍照指引
				</view>
				<view v-if="!imgaddress" class="imgEmpty" @click="chooseImage">
					<view class="takePhoto">
						<image src="@/static/images/camera.png" mode="" />
						<view>点击拍照</view>
					</view>
				</view>
				<view class="fillImg" v-else>
					<image @click="fullview" class="imgaddress" :src="imgaddress" mode="aspectFill" />
					<!-- ai合规情况结论 S -->
					<view :class="['ai-result', ['gre', 'org', 'red'][aiResult - 1]]" v-if="aiResult">
						<image class="ai-result-ico" src="@/static/images/ai.svg"></image>
						<text>
							{{ ['合规', '疑似合规', '不合规'][aiResult - 1] }}
						</text>
					</view>
					<!-- ai合规情况结论 E -->
					<view class="rebate" @click.stop="chooseImage">
						<image src="@/static/images/rebate.png" mode="" />
						<view>重拍</view>
					</view>
				</view>
			</view>
		</view>

		<!-- <view @click="handleTimeUpdate">测试</view> -->
		<view class="bottom">
			<view class="btn" @click="handleSign">{{
				signType == "1" ? "签到" : "签退"
			}}</view>
		</view>
		<!-- 日历 日周月组件  -->
		<weekYearDate ref="weekYear" :showState="showState" @selectChange="selectChange" @bindClose="bindClose" />
		<previewMedia ref="previewMedia"></previewMedia>
		<!-- 维修工单目前还不需要签到签退指引 -->
		<cameraGuide v-if="orderType == 1||orderType == 2" :orderType="orderType" @loaded="guideLoaded" :signType="signType" ref="cameraGuide"></cameraGuide>
	
	</view>
</template>

<script>
import GlobalNavBar from '@/components/uni-nav-bar/global-nav-bar';
import cameraGuide from '@/components/camera-guide/camera-guide.vue';
import {
	elevtorDetail,
	changeElevatorState,
	changeElevatorStoplog,
} from '@/apis/elevator.js';
import { fetchDetail } from '@/apis/repair.js';
import { getPlanDetail } from '@/apis/workOrder.js';
import { getOffairDetail } from '@/apis/affair.js';
import weekYearDate from '@/components/dateSelect/index.vue';
import dayjs from 'dayjs';
import { getConfig, timeUpdate } from '@/apis/sign.js';
import { getlocalinfo } from '@/utils/utils.js';
import { getDistance } from '@/utils/tools.js';
import { signIn, signOut } from '@/apis/workOrder.js';
import { mapState, mapActions } from 'vuex';
import { getBeforeDate } from '@/utils/utils';
import { getLocalPlan, setSyncData } from '@/utils/offline.js';
import { removePath, getPathInfo, setPath } from '@/utils/watermarkTool.js';
import { MODEL_ID_MAP } from '@/utils/constants.js';
import md5 from 'js-md5';

// 工单使用模型标记
const kMODALRESULT = {
	// 保养工单
	1: true, 
	// 维修工单
	2: true, 
	// 配件工单
	3: false, 
	// 事务工单
	5: false, 
	// 质检工单
	6: false, 
};

export default {
	components: {
		GlobalNavBar,
		weekYearDate,
		cameraGuide
	},
	props: {
		// 1页面模式  2组件模式
		pageType: {
			type: [Number, String],
			default: 1
		}
	},

	data() {
		return {
			// 离线数据
			offlineDetail: {},
			systemTime: {
				hour: 0,
				min: 0,
			},
			// 是否提交中
			loading: false,
			showchangeTips: false,
			planId: '',
			elevatorId: '',
			signType: '',
			isStop: '',
			showBg: false,
			planDetail: {},
			elevatorDetail: {
				buildingName: '',
				elevatorAddress: '',
				// isStop: 1,
			},
			dayjs: dayjs,
			showState: false,
			// finishFlag: "", //是维修完成还是中途签退
			config: {},
			finishDate: '',
			dateArr: [
			],
			locationError: '',
			imgaddress: '',
			signImg: [],
			parentStyle: '0;',
			// 是否填充上次的签到签退图片
			useLastImg: false,
			// 工单类型
			orderType: 2,
			// 判断返回后是否立即执行维修完成
			isFinsh: false,
			// 后台根据按钮类型推送消息
			buttonType: null,
			// 实际当前定位的经纬度
			localInfo: {},
			aiResult: '',
			// 拍照指引
			guide: {},
		};
	},
	computed: {
		...mapState('user', ['userinfo']),
		...mapState('system', ['onlineStatus']),
		// 是否离线  false离线 true

		// 是否显示拍照片
		isTakePhoto() {
			// 如果是签到 signType:1=>签到,2=>签退,orderType:1=>保养 2=>维修 3=>配件,5=>事务工单

			// 如果是签到
			if (this.signType == 1) {
				switch (this.orderType) {
				// 如果是保养
				case 1:
					return this.config.cheSignIn == 1;
				case 2:
					return this.config.malSignIn == 1;
				case 3:
					return this.config.partSignIn == 1;
				case 5:
					return this.config.affairSigin == 1;
				case 6:
					return this.config.checkSigin == 1;
				case 9:
					return true;
				}
			} else {
				switch (this.orderType) {
				// 如果是保养
				case 1:
					return this.config.cheSignOut == 1;

				case 2:
					return this.config.malSignOut == 1;
				case 3:
					return this.config.partSignOut == 1;
				case 5:
					return this.config.affairSignOut == 1;
				case 6:
					return this.config.checkSignOut == 1;
				case 9:
					return true;
				}
			}
			return true;
		},
		todayStr() {
			if (!this.finishDate) {
				return '';
			}
			let today = getBeforeDate(0);
			let tomorrow = getBeforeDate(-1);
			let afterTomorrow = getBeforeDate(-2);
			let str = this.finishDate.substring(0, 10);
			if (str == today) {
				return '今天';
			} else if (str == tomorrow) {
				return '明天';
			} else if (str == afterTomorrow) {
				return '后天';
			} else {
				return '';
			}
		},
		// 展示预计完成时间,只有签到且是保养维修才显示
		showFinshTime() {
			return (
				this.signType == '1' && (this.orderType == 1 || this.orderType == 2)
			);
		},
	},
	async onLoad(e) {
		console.log(e, 'e的值');
		this.planId = e.planId;
		this.elevatorId = e.elevatorId;

		if (e.isFinsh) {
			this.isFinsh = JSON.parse(e.isFinsh) || false;
		}
	},
	onShow() {
		if (this.signType) {
			// #ifdef H5
			console.log(`[sign/index.vue] this.signType.toString() :${this.signType.toString()}`);
			if (this.signType.toString() === '1') {
				uni.setNavigationBarTitle({
					title: '签到'
				});
			} else {
				uni.setNavigationBarTitle({
					title: '签退'
				});
			}
			// #endif
			return;
		}

		this.init({});
	},
	beforeDestroy() {
		uni.$off('uploadImg');
	},
	methods: {
		...mapActions('user', ['handleRreshToken']),
		// 指引加载完成
		guideLoaded(res) {
			console.log('guideLoaded', this.orderType, res);
			this.guide = res || {};
		},
		openGuide() {
			this.$refs.cameraGuide.open();
		},
		async init() {
			console.log('init');
			uni.showLoading({
				title: '加载中',
				mask: true
			});
			uni.setNavigationBarTitle({ title: '' });
			uni.getStorage({
				key: 'signObj',
				success: async (res) => {
					this.signType = res.data.signType;
					if (this.onlineStatus) {
						await this.getConfig();

						// this.locationError = this.isErrorLocation();
						this.isErrorLocation();
					} else {
						uni.getStorage({
							key: 'offline_config',
							success: (res) => {
								this.config = res.data;
							}
						});
					}

					// #ifdef H5
					console.log(`[sign/index.vue] this.signType.toString() :${this.signType.toString()}`);
					if (this.signType.toString() === '1') {
						uni.setNavigationBarTitle({
							title: '签到'
						});
					} else {
						uni.setNavigationBarTitle({
							title: '签退'
						});
					}
					// #endif
					this.useLastImg = res.data.useLastImg;
					this.orderType = res.data.orderType;
					// this.isStop = this.signType == 1 ? 2 : 1;
					this.buttonType = res.data.buttonType;
					await this.elevtorDetail(); 
					if (this.orderType == 2) {
						// 维修工单
						await this.getDetail();
					} else {
						if (this.onlineStatus) {
							// 保养工单
							await this.getPlanDetail();
						}
					} 
					await this.getNowDate();
					uni.hideLoading();
				},
				fail: () => {
					uni.hideLoading();
				},
			});
		},
		fullview() {
			this.$previewMedia({
				sources: [this.imgaddress],
				current: 0
			});
		},
		async upload(path, imgId, options) {
			if (!path) {
				return;
			}
			uni.showLoading({
				title: '上传中',
			});
			let data = path;
			if (this.onlineStatus) {
				try {
					const ups = await this.http.upload(data, imgId, options);
					if (ups.data) {
						data = ups.data.link;
					} else {
						console.log('图片上传失败', ups);
						uni.showToast({
							title: '图片上传失败',
							icon: 'none',
						});
						data = '';
					}
				} catch (error) {
					console.log('图片上传失败error', error);
					uni.showToast({
						title: '图片上传失败',
						icon: 'none',
					});
					data = '';
				}
			}
			this.imgaddress = data;
			uni.hideLoading();
			return data;
		},

		getHeadInfo(url) {
			if (url.indexOf('aliyuncs.com') == -1) {
				return getPathInfo(url);
			}
			return new Promise((resolve) => {
				// #ifdef H5
				this.http.head(url).then(header => {
					const newHeader = {};
					Object.keys(header).forEach(key => {
						// 转码，兼容中文字符 
						newHeader[key] = decodeURIComponent(header[key]);
					});
					resolve(newHeader);
				});
				// #endif

				// #ifndef H5
				uni.request({
					method: 'HEAD',
					url,
					success(res) {
						let header = res.header || {};
						Object.keys(header).forEach(key => {
							// 转码，兼容中文字符
							header[key] = decodeURIComponent(header[key]);
						});
						resolve(header);
					}, fail() {
						resolve({});
					}
				});
				// #endif
			});
		},

		async chooseImage() {
			// 选择图片 
			try {
				uni.$off('uploadImg');
			} catch (error) {
				console.log(error);
			}

			uni.$once('uploadImg', async (path, imgId, options) => {
				const parseJsonSafely = (jsonString) => {
					if (!jsonString) {
						return {};
					}
					if (typeof jsonString === 'object') {
						return options;
					}
					try {
						return JSON.parse(jsonString);
					} catch (error) {
						console.error('解析 JSON 失败:', error);
						return null;
					}
				};

				let imgInfo = options ? parseJsonSafely(options) : await this.getHeadInfo(path);
				console.log('imgInfo', imgInfo,path, imgId, options);

				let result = 3;
				if (imgInfo['result'] !== '') {
					if (imgInfo.model_result && imgInfo.model_result.business_result !== undefined && imgInfo.model_result.business_result !== '') {
						result = Number(imgInfo.model_result.business_result) + 1;
					} else {
						result = Number(imgInfo['result']) + 1;
					}
					this.aiResult = result;
				} else {
					this.aiResult = '';
				}
				 
				// #ifdef MP-WEIXIN
				if (this.imgaddress) {
					removePath(this.imgaddress);
				}
				// #endif

				// #ifdef H5  
				const userModalResult = kMODALRESULT[this.orderType] || false; 
				// 判断是否使用模型数据
				console.log(`[sign/index.vue] 使用模型数据 orderType:${this.orderType}`, userModalResult);
				console.log(`[sign/index.vue] 使用模型数据 options:${options}`);
				const optionsObj = JSON.parse(options);
				const md5Path = md5(path);
				setPath(md5Path, imgId);
				let obj;
				if (userModalResult) {
					obj = {
						imgId,
						planId: this.planId,
						type: this.signType.toString() === '1' ? '1' : '2',
						result: `${optionsObj.result}`,
						// model_id: this.signType.toString() === '1' ? '3b4caf46-75a1-44c2-9678-097c403a158c' : '04521863-0472-44be-b159-f3eeb2920916',
						model_id: MODEL_ID_MAP[`${this.signType}`],
						watermark: JSON.stringify(optionsObj.watermark),
						model_result: JSON.stringify(optionsObj.model_result),
						business_result: JSON.stringify(optionsObj.business_result),
						ai_business_config: JSON.stringify(optionsObj.ai_business_config),
					};
				} else {
					obj = {
						imgId,
						planId: this.planId,
						type: this.signType.toString() === '1' ? '1' : '2',
						watermark: JSON.stringify(optionsObj.watermark),
						result: '',
						model_result: '',
						business_result: '',
					};
				}
				console.log(`[sign/index.vue] 水印数据 ${JSON.stringify(obj)}`);
				await this.setWatermarkJson(obj);
				// #endif

				// 显示图片
				this.imgaddress = path;
			});
			// if (!this.localInfo.longitude && this.onlineStatus) {
			// 	uni.showToast({
			// 		title: '获取定位失败',
			// 		mask: true,
			// 	});
			// 	return;
			// }
			// 设置缓存
			let data = {
				buildingId: this.elevatorDetail.buildingId,
				buildingName: this.elevatorDetail.buildingName,
				elevatorId: this.elevatorId,
				elevatorAddress: this.elevatorDetail.elevatorAddress,
				planId: this.planId,
				planWorkItemId: '',
				partsId: '',
			};
			uni.setStorage({
				key: 'waterMarkMsg',
				data,
				success: async () => {
					const imgType = this.signType == 1
						? { 1: 2, 2: 5, 3: 8, 5: '', 6: '' }[this.orderType]
						: { 1: 3, 2: 6, 3: 7, 5: '', 6: '' }[this.orderType];
					const isOffline = this.offLine ? '1' : '0';
					const guideStatus = this.guide?.images?.length ? '1' : '0';
					
					// 判断是否存在auditType 

					// 维修工单使用AI业务配置
					const useAIBusinessConfig = this.orderType === 2;
					console.log('useAIBusinessConfig', useAIBusinessConfig);
					let url = `/pages/camera/camera?useNow=0&imgType=${imgType}&offLine=${isOffline}&guideStatus=${guideStatus}&auditType=${this.planDetail.auditType}`;

					// #ifdef H5
					// 如果auditType存在且不为1(非年审类型)，且imgType为3(签退)，则使用模型
					// 判断是否为年审类型且为签退
					const isAuditTypeYear = this.planDetail.auditType !== undefined
						&& this.planDetail.auditType !== null && `${this.planDetail.auditType}` === '1';
					const isSignOut = String(imgType) === '3';
					
					const shouldPassModel = (isAuditTypeYear && isSignOut) || imgType === undefined;

					// 如果imgType为空，则不使用模型
					if (shouldPassModel) {
						url = `/pages/camera/camera?useNow=0&imgType=0&offLine=${isOffline}&guideStatus=${guideStatus}&modelType=0`;
					} else {
						url = `/pages/camera/camera?useNow=0&imgType=${imgType}&offLine=${isOffline}&guideStatus=${guideStatus}&useAIBusinessConfig=${useAIBusinessConfig}`;
					}
					// #endif

					console.log('url', url);
					
					uni.navigateTo({
						url: url,
						fail: (err) => {
							console.log(err);
						},
					});
				},
			});
			//  return
		},

		async handleSign() {
			if (this.loading) {
				return;
			}
			if (!this.imgaddress && this.isTakePhoto) {
				uni.showToast({
					title: `${this.signType == 1 ? '请拍摄入场照' : '请拍摄退场照'}`,
					icon: 'none',
					mask: true,
				});
				return;
			}
			if (!this.isStop) {
				uni.showToast({
					title: '请选择当前电梯状态',
					icon: 'none',
				});
				return;
			}
			if (!this.onlineStatus && this.orderType == 1) {
				// 离线保养签到
				let formData = {
					signType: this.signType,
					userId: this.userinfo.user_id,
					planId: this.planId,
					signImage: this.imgaddress,
					signDesc: '',
					signStatus: 3,
					elevatorId: this.elevatorId,
					signTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
					elevatorStatus: this.isStop,
					finishDate: this.finishDate,
					isStop: this.isStop,
				};
				await setSyncData('signList', formData);
				console.log('保存离线签到缓存记录', formData);
				uni.showToast({
					title: '已离线签到,待同步',
					icon: 'none',
					mask: true,
				});
				this.backFuc();
				return;
			}

			this.loading = true;
			uni.showLoading({
				title: '提交中',
				mask: true,
			});
			if (this.imgaddress && this.imgaddress.indexOf('aliyuncs.com') == -1) {
				try {
					const ups = await this.http.upload(this.imgaddress);

					console.log('[ups]:', ups);

					if (ups.data) {
						this.imgaddress = ups.data.link;
					} else {
						console.log('图片上传失败', ups);
						uni.showToast({
							title: '图片上传失败',
							icon: 'none',
						});
						this.loading = false;
						return;
					}
				} catch (error) {
					uni.showToast({
						title: '图片上传失败',
						icon: 'none',
					});
					this.loading = false;
					return;
				}
			}

			let localInfo = await this.getLocalInfo();
			if (!localInfo.latitude) {
				uni.showModal({
					title: '提示',
					content: '请打开定位，再签到',
					showCancel: false,
				});
				// return;
			}
			// 计算是否范围内打卡
			let distance = getDistance(
				localInfo.latitude,
				localInfo.longitude,
				this.elevatorDetail.latitude,
				this.elevatorDetail.longitude
			);
			let address = {};
			try {
				address = await getlocalinfo(localInfo.latitude, localInfo.longitude);
				console.log('address', address);
			} catch (error) {
				console.log('error', error);
			}

			let signStatus = 1;
			if (!localInfo.latitude) {
				this.locationError = '无定位';
			}
			if (distance > this.$config.maxDistance) {
				signStatus = 2;
				this.locationError = '偏离项目定位';
			} else {
				this.locationError = '正常';
			}
			// 判断是签到还是签退

			let that = this;
			(this.signType == 1 ? signIn : signOut)(
				this.signType == 1
					? {
						userId: that.userinfo.user_id,
						planId: that.planId,
						signImage: that.imgaddress,
						signStatus: signStatus,
						isStop: this.isStop,
						signLongitude: localInfo.longitude,
						signLatitude: localInfo.latitude,
						signAddress: address.result.address,
						finishDate: `${this.finishDate}${this.finishDate && this.finishDate.length < 18 ? ':00' : ''}`,
					}
					: {
						userId: that.userinfo.user_id,
						planId: that.planId,
						isStop: this.isStop,
						signOutImage: that.imgaddress,
						signOutStatus: signStatus,
						signOutLongitude: localInfo.longitude,
						signOutLatitude: localInfo.latitude,
						signOutAddress: address.result.address,
						buttonType: this.buttonType,
					}
			).then(async (res) => {
				that.reportAddress({
					longitude: localInfo.longitude,
					latitude: localInfo.latitude,
					userId: that.userinfo.user_id,
					operation: that.signType == 1 ? 2 : 3,
					planId: that.planId,
					isStop: this.isStop,
					recordType: 1, // 工单定位
				}); // 定位上报埋点

				// console.log(this.isFinsh, "完成标识");
				await this.changeStatus();
				if (this.isStop != this.elevatorDetail.isStop) {
					// 如果修改了电梯状态  发送通知

				}
				uni.hideLoading();
				this.loading = false;
				uni.showToast({
					title: '提交成功',
					icon: 'none',
					mask: true,
				});
				this.$store.dispatch('user/getPlanLatitudePlus');// 更新数据 用于电子围栏判断
				setTimeout(() => {
					this.backFuc();
					uni.$emit('isFinsh', this.isFinsh);
				}, 600);
			}).catch(()=>{
				this.loading = false;
			});
		},
		getNumText(num) {
			return num > 9 ? num : '0' + '' + Number(num);
		},

		// 预计完成时间提交
		handleTimeUpdate() {
			timeUpdate({
				id: this.planId,
				finishDate: this.finishDate,
			}).then((res) => {
				if (res) {
				}
			});
		},
		// 初始化时间
		getNowDate() {
			console.log('初始化时间');
			return new Promise((resolve) => {
				uni.showLoading({
					icon: 'none',
				});
				let mind = 0;
				// 如果是维修+2两个小时
				if (this.orderType == 2) {
					console.log('维修签到');
					mind = mind + 60 * 2;
				} else {
					let timelist = this.planDetail.templateInfo || [];
					for (let i = 0; i < timelist.length; i++) {
						mind = mind + (timelist[i].workDay || 0) * 60 * 24;
						mind = mind + (timelist[i].workHour || 0) * 60;
						mind = mind + (timelist[i].workMin || 0);
					}
					if (!this.onlineStatus) {
						mind = 30; // 离线默认半小时
					}

					console.log(mind, '保养min的值 保养签到');
					this.systemTime = {
						hour: Math.floor(mind / 60),
						min: mind % 60,
					};
				}
				let times = mind * 60 * 1000 + new Date().getTime();
				let date = dayjs(times).format('YYYY-MM-DD');
				let hour = this.getNumText(dayjs(times).format('HH'));
				let min = this.getNumText(dayjs(times).format('mm'));
				let arr = [...date.split('-'), hour, min];
				this.dateArr = arr;
				if (this.signType == 1) {
					this.finishDate = `${date} ${hour}:${min}`;
				} else {
					this.finishDate = this.planDetail.finishDate;
				}
				console.log('初始化预计时间', arr, this.systemTime);

				uni.hideLoading();
				resolve({});
			});
		},
		// 获取选择的时机
		selectChange(res) {
			this.finishDate = res.date;
			let timeArr = res.date.replace(' ', ':').replace(/\:/g, '-').split('-');
			this.dateArr = timeArr;
		},
		showChooseDate() {
			this.showState = true;
			this.$refs.weekYear.$refs.chooseDate.open();
		},
		bindClose() {
			this.$refs.weekYear.$refs.chooseDate.close();
			this.showState = false;
		},
		handleClickStatus(isStop) {
			// console.log("点击");
			// this.isStop = this.isStop == 1 ? 2 : 1;
			this.isStop = isStop;
		},
		changeStatus() {
			return new Promise((resolve) => {
				changeElevatorState({
					id: this.elevatorId,
					isStop: this.isStop,
				})
					.then(async () => {
						changeElevatorStoplog({
							elevatorId: this.elevatorId,
							initStatus: this.elevatorDetail.isStop,
							setStatus: this.isStop,
							module: `${this.planId}`,
							position: this.signType == 1 ? 1 : 2
						}).then(() => {
							resolve({});
						});
					})
					.catch(() => {
						uni.hideLoading();
					});
			});
		},
		// 维修工单详情
		getDetail() {
			uni.showLoading({
				title: '加载中',
				icon: 'none',
			});
			return new Promise((resolve) => {
				fetchDetail({ planId: this.planId }).then((res) => {
					// console.log(res, 777);
					this.planDetail = res.data;
					if (this.useLastImg == true) {
						let url = '';
						url =
							this.signType == 1
								? this.planDetail.lastSignImg?.signImage || ''
								: this.planDetail.lastSignImg?.signOutImage || '';
						this.imgaddress = url;

						// console.log(this.signType, this.signType == 1 ? "签到" : "签退");
					} else {
						this.imgaddress = '';
					}
					uni.hideLoading();

					resolve();
				});
			});
		},
		// 保养工单详情
		getPlanDetail() {
			return new Promise((resolve) => {
				getPlanDetail({ planId: this.planId })
					.then(async (res) => {
						this.planDetail = res.data;
						if (this.useLastImg == true) {
							let url = '';
							url =
								this.signType == 1
									? this.planDetail.lastSignImg?.signImage || ''
									: this.planDetail.lastSignImg?.signOutImage || '';
							this.imgaddress = url;

							console.log(this.signType, this.signType == 1 ? '签到' : '签退');
							let imgInfo;
							try {
								imgInfo = await this.getHeadInfo(url);
							} catch (error) {
								console.log(`[getPlanDetail] error:${error}`);
							}

							if (imgInfo['result'] !== '') {
								this.aiResult = Number(imgInfo['result']) + 1;
							} else {
								this.aiResult = '';
							}
							if (imgInfo['x-oss-meta-result']) {
								this.aiResult = Number(imgInfo['x-oss-meta-result']) + 1;
							} else {
								this.aiResult = '';
							}
						} else {
							this.imgaddress = '';
						}
						resolve();
					})
					.catch(() => {
						resolve();
					});
			});
		},
		// 事务工单详情
		getAffairDetail() {
			return new Promise((resolve) => {
				getOffairDetail({ planId: this.planId })
					.then((res) => {
						this.planDetail = res.data;
						if (this.useLastImg == true) {
							let url = '';
							url =
								this.signType == 1
									? this.planDetail.lastSignImg?.signImage || ''
									: this.planDetail.lastSignImg?.signOutImage || '';
							this.imgaddress = url;

							console.log(this.signType, this.signType == 1 ? '签到' : '签退');
						} else {
							this.imgaddress = '';
						}
						resolve();
					})
					.catch(() => {
						resolve();
					});
			});
		},
		elevtorDetail() {
			return new Promise(async (resolve) => {
				if (!this.onlineStatus) {
					// 离线情况，拿缓存
					this.offlineDetail = await getLocalPlan(this.planId);
					this.getNowDate();
					return;
				}
				elevtorDetail({ elevatorId: this.elevatorId })
					.then((res) => {
						this.offline = false;
						this.elevatorDetail = res.data;
						resolve();
					})
					.catch((err) => {
						// 获取失败 拿缓存
						uni.getStorage({
							key: 'offline_detail',
							success: (res) => {
								this.offlineDetail = res.data;
								if (this.signType == 2) {

								}
								resolve();
							},
						});
					});
			});
		},
		getConfig() {
			return new Promise((resolve) => {
				getConfig()
					.then((res) => {
						if (res) {
							this.config = res.data.config;
						}
						resolve();
					})
					.catch((err) => {
						uni.getStorage({
							key: 'offline_config',
							success: (res) => {
								this.config = res.data;
								resolve();
							},
							fail: (fail) => {
								resolve();
							},
						});
					});
			});
		},

		// 界面返回
		backFuc() {
			if (this.orderType == 1) {
				if (this.pageType == 2) {
					// 组件模式
					this.$emit('back', {
						planId: this.planId,
						elevatorId: this.elevatorId
					});
					return;
				}

				// #ifdef H5 
				uni.navigateBack(); // h5 版本统一back
				// #endif

				// #ifdef MP-WEIXIN
				// 保养
				const pages = getCurrentPages();
				console.log('pages', pages);
				if (pages.length < 2 || pages[pages.length - 2].route.indexOf('workOrders/detail') == -1) {
					uni.redirectTo({
						url: `/subpages/workOrders/detail?planId=${this.planId}&elevatorId=${this.elevatorId}` // 兼容小程序断网页面堆栈被销毁问题
					});
				} else {
					uni.navigateBack();
				}
				// #endif
			} else {
				uni.navigateBack();
			}
		},
		// 判断是否定位异常
		async isErrorLocation() {
			let localInfo = await this.getLocalInfo();
			this.localInfo.latitude = localInfo.latitude;
			this.localInfo.longitude = localInfo.longitude;

			if (!localInfo.latitude) {
				uni.showModal({
					title: '提示',
					content: '请打开定位，再签到',
					showCancel: false,
				});
				// return
			}
			// 计算是否范围内打卡
			let distance = getDistance(
				localInfo.latitude,
				localInfo.longitude,
				this.elevatorDetail.latitude,
				this.elevatorDetail.longitude
			);
			if (!localInfo.latitude) {
				this.locationError = '无定位';
			}
			if (distance > this.$config.maxDistance) {
				this.locationError = '偏离项目定位';
			} else {
				this.locationError = '正常';
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.sigin {
	background: #f3f6f8;
	height: 100vh;
	color: #333;

	.nav {
		position: sticky;
		top: 0;
		z-index: 10;
	}

	.bg {
		width: 302rpx;
		height: 366rpx;
		position: absolute;
		top: 0;
		right: 0;
	}

	.title {
		display: flex;
		justify-content: space-between;
		padding: 32rpx 20rpx 20rpx 40rpx;

		.left {
			font-size: 42rpx;
			color: #333;
			font-weight: 500;
			width: 540rpx;
		}

		.right {
			padding: 10rpx 20rpx;
			background: #ffffff;
			border-radius: 8rpx;
			display: flex;
			font-size: 26rpx;
			position: absolute;
			font-weight: 500;
			right: 20rpx;

			.statusSwich {
				width: 32rpx;
				height: 32rpx;
				margin-top: 5rpx;
				margin-left: 6rpx;
			}
		}
	}

	.content {
		margin: 0rpx 20rpx;
		background: #f3f6f8;
		border-radius: 8rpx;

		.top {
			position: relative;
			z-index: 12;
		}

		.content_item {
			display: flex;
			padding: 24rpx 20rpx;
			margin-bottom: 16rpx;
			background: #fff;
			justify-content: space-between;
			font-size: 28rpx;
			border-radius: 8rpx;
			align-items: center;

			image {
				width: 32rpx;
				height: 32rpx;
				margin-top: 4rpx;
			}

			.name {
				display: flex;
			}

			.label {
				width: 240rpx;
			}

			.buildName {
				width: 470rpx;
			}

			.status-btns {
				display: flex;
				align-items: center;
				justify-content: flex-end;

				&-item {
					width: 176rpx;
					height: 48rpx;
					border: 2rpx solid #cccccc;
					border-radius: 8rpx;
					font-size: 27rpx;
					text-align: center;
					color: #666;
					line-height: 48rpx;
				}

				&-item:last-child {
					margin-left: 16rpx;
				}
			}

			.error-tips {
				width: 100%;
				text-align: right;
				color: #e02020;
				font-size: 24rpx;
				font-weight: normal;
				margin-top: 5rpx;

				image {
					width: 1rem;
					height: 1rem;
					vertical-align: -0.2rem;
				}
			}

			.status-act {
				border-color: #0091ff;
				color: #0091ff;
			}

			// .status {
			//   display: flex;
			// }
			// .status_item {
			//   display: flex;
			//   padding: 4rpx 8rpx;
			//   border-radius: 8rpx;
			//   border: 1rpx solid #ccc;
			// }
			// .active {
			//   background: #0091ff;
			//   color: #fff;
			//   border: none;
			// }
			.error {
				color: #e02020;
				font-size: 24rpx;
				width: 200rpx;
				justify-content: flex-end;
				display: flex;
			}

			.timeArea {
				display: flex;
				align-items: center;

				image {
					width: 32rpx;
					height: 32rpx;
					margin-left: 4rpx;
				}
			}
		}

		.imgbox {
			margin-bottom: 16rpx;
			padding: 24rpx 20rpx;
			background: #fff;
			border-radius: 8rpx;
			position: relative;

			.guide {
				position: absolute;
				right: 20rpx;
				top: 20rpx;
				display: flex;
				align-items: center;
				justify-content: flex-end;
				font-size: 28rpx;
				color: #666666;

				&-ico {
					width: 28rpx;
					height: 28rpx;
					margin-right: 4rpx
				}
			}

			.imgEmpty {
				width: 100%;
				height: 640rpx;
				background: #f7f7f8;
				margin-top: 16rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-size: 28rpx;
				color: #0091ff;

				.takePhoto {
					width: 200rpx;
					height: 200rpx;
					height: 200rpx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					// background: red;
					image {
						width: 72rpx;
						height: 72rpx;
					}
				}
			}

			.fillImg {
				display: flex;
				justify-content: center;
				align-items: center;
				padding-top: 16rpx;
				position: relative;

				.ai-result {
					position: absolute;
					top: 40rpx;
					right: 32rpx;
					display: flex;
					align-items: center;
					border-radius: 8rpx;
					color: #fff;
					font-size: 28rpx;
					padding: 2rpx 12rpx 6rpx 12rpx;
					vertical-align: unset;
					font-weight: normal;

					&-ico {
						width: 28rpx;
						height: 28rpx;
						margin-right: 4rpx;
					}
				}

				.gre {
					background-color: #68CA00;
				}

				.org {
					background-color: #FF7505;
				}

				.red {
					background-color: #E02020;
				}

				.imgaddress {
					width: 100%;
					height: 640rpx;
				}

				.rebate {
					image {
						width: 36rpx;
						height: 36rpx;
					}

					width: 96rpx;
					height: 96rpx;
					position: absolute;
					bottom: 80rpx;
					background: #0091ff;
					color: #fff;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					border-radius: 50%;
				}
			}
		}
	}

	.bottom {
		width: 100%;
		height: 98rpx;
		background: #ffffff;
		position: fixed;
		padding: 0rpx;
		display: flex;
		bottom: 0;
		align-items: center;
		border-top: 2rpx solid #eee;

		.btn {
			width: calc(100% - 40rpx);
			height: 70rpx;
			background: #0091ff;
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			margin: 0 auto;
		}
	}
}
</style>
